/*
 * @Author: tanjunyi@doctorwork.com
 * @Date: 2020-10-12 14:40:51
 * @LastEditors: tanjunyi@doctorwork.com
 * @LastEditTime: 2020-10-17 21:44:01
 * @Description: 
 * 签名算法 ：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
 * 算法测试 ： http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
 */
'use strict'

var fs = require('fs');
var xml2js = require('xml2js');
var Promise = require('bluebird');
var crypto = require('crypto');


// 将url拼装
exports.toUrl = function (url = '/', params = {}) {
	if (JSON.stringify(params) != '{}') {
		url += url.indexOf('?') >= 0 ? '&' : '?';
		for (var param in params) {
			url += url[url.length - 1] == '?' ? '' : '&';
			url += (param + '=' + params[param]);
		}
	}
	return url;
}
// 读文件
exports.readFileAsync = function (fpath, encoding) {
	return new Promise(function (resolve, reject) {
		fs.readFile(fpath, encoding, function (err, content) {
			if (err) { reject(err) }
			else resolve(content);
		})
	})
}
// 写文件
exports.writeFileAsync = function (fpath, content) {
	return new Promise(function (resolve, reject) {
		fs.writeFile(fpath, content, function (err, content) {
			if (err) { reject(err) }
			else resolve();
		})
	})
}
// 解析xml
exports.xmlToJson = function (xml) {
	return new Promise(function (resolve, reject) {
		xml2js.parseString(xml, { trim: true }, function (err, content) {
			if (err) { reject(err) }
			else resolve(content)
		})
	})
}

// 消息格式化
exports.formatMessage = function formatMessage(result) {
	var message = {}
	if (typeof result == 'object') {
		var keys = Object.keys(result)

		for (var i = keys.length - 1; i >= 0; i--) {
			var item = result[keys[i]];
			var key = keys[i]

			if (!(item instanceof Array) || item.length == 0) {
				continue;
			}
			if (item.length == 1) {
				var val = item[0];
				if (typeof val == 'object') {
					message[key] = formatMessage(val)
				} else {
					message[key] = (val || '').trim()
				}
			}
			else {
				message[key] = []
				for (var j = item.length - 1; j >= 0; j--) {
					message[key].push(formatMessage(item[j]))
				}
			}
		}
	}
	return message;
}



/**
 * 网页授权签名算法
 * @param {*} ticket 
 * @param {*} url 
 */
exports.sign = function sign(ticket, url) {
	var noncestr = createNonce();
	var timestamp = createTimeTamp();
	var signature = _sign(noncestr, ticket, timestamp, url);
	return {
		noncestr: noncestr,
		timestamp: timestamp,
		signature: signature
	}
}
var createNonce = function () {
	return Math.random().toString(36).substr(2, 15);
}

var createTimeTamp = function () {
	return parseInt(new Date().getTime() / 1000, 10) + '';
}
var _sign = function (noncestr, ticket, timestamp, url) {
	var params = [
		'noncestr=' + noncestr,
		'jsapi_ticket=' + ticket,
		'timestamp=' + timestamp,
		'url=' + url
	]
	var str = params.sort().join('&');
	var shasum = crypto.createHash('sha1');
	shasum.update(str);
	return shasum.digest('hex');
}